package com.student.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;

import com.student.dao.StudentDao;
import com.student.entity.Page;
import com.student.entity.Student;

@Repository("studentDao")
public class StudentDaoImpl implements StudentDao {

	@Autowired
	private SessionFactory sessionFactory;

	private Session getSession() {
		return this.sessionFactory.openSession();
	}


	public List<Student> selStudent(Page page) {
		Session session=this.getSession();
		List<Student> list=session.createQuery("from Student").setFirstResult((page.getCurrentPage()-1)*page.getShowCount()).setMaxResults(page.getShowCount()).list();
		session.close();
		return list;
	}

	public void addStudent(Student stu) {
		Session session=this.getSession();
		Transaction tran=null;
		try {
			tran=session.beginTransaction();
			session.save(stu);
			tran.commit();
		} catch (Exception e) {
			tran.rollback();
		}finally{
			session.close();
		}
	}

	public void updateStudent(Student stu) {
		Session session=this.getSession();
		Transaction tran=null;
		try {
			tran=session.beginTransaction();
			session.update(stu);
			tran.commit();
		} catch (Exception e) {
			tran.rollback();
		}finally{
			session.close();
		}
	}

	public void delStudent(Integer id) {
		Session session=this.getSession();
		Transaction tran=null;
		try {
			tran=session.beginTransaction();
			session.delete(this.selStudent(id));
			tran.commit();
		} catch (Exception e) {
			tran.rollback();
		}finally{
			session.close();
		}
	}

	public Student selStudent(Integer id) {
		Session session=this.getSession();
		Student stu=(Student)session.get(Student.class, id);
		session.close();
		return stu;
	}

	public int getTotalResult() {
		Session session=this.getSession();
		int count=session.createQuery("from Student").list().size();
		session.close();
		return count;
	}


	public static void main(String[] args) {
		ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
		StudentDao g=(StudentDaoImpl)ctx.getBean("studentDao");
//		Student s=new Student();
//		s.setId(1);
//		s.setName("妞妞");
//		s.setAge(28);
//		s.setSex("女");
//		s.setTel("13969069124");
//		s.setAddress("北京");
//		s.setBirthday("1888-4-1");
//		g.updateStudent(s);
		g.delStudent(28);
	}
}
